<?php
declare(strict_types=1);

namespace SixShop\Lakala\Hook;

use app\event\OrderDetailResponseEvent;
use app\model\Order;
use SixShop\Core\Attribute\Hook;
use SixShop\Lakala\Enum\WechatOrderStateEnum;
use SixShop\Payment\Model\ExtensionPaymentModel;
use SixShop\Wechat\Service\ExpressService;

class OrderHook
{
    public function __construct(private ExpressService $expressService)
    {
    }

    /**
     * 拉卡拉订单信息
     */
    #[Hook(OrderDetailResponseEvent::class)]
    public function orderInfo(OrderDetailResponseEvent $event): void
    {
        $order = $event->getOrderModel();
        if ($order->payment_method == 'lakala' && $order->shipping_status == 1) {
            $payment = ExtensionPaymentModel::where([
                'order_id' => $order->id,
                'biz_type' => 1,
                'pay_type' => 'lakala'
            ])->findOrEmpty();
            if (!$payment->isEmpty()) {
                $wechatTransactionID = $payment['payment_result']['acc_trade_no'];
                $orderInfo = $this->expressService->queryOrder($wechatTransactionID);
                $orderState = WechatOrderStateEnum::from($orderInfo['order_state']);
                $order->setAttr('lakala', [
                    'wechat_transaction_id' => $wechatTransactionID,
                    'wechat_order_state' => $orderState,
                    'openid' => $payment['payment_result']['acc_resp_fields']['user_id'],
                ]);
                if ($orderState == WechatOrderStateEnum::TRADE_COMPLETED && $order->order_status == 30) {
                    // 订单完成
                    Order::update([
                        'order_status' => 40,
                        'confirm_time' => date('Y-m-d H:i:s'),
                        'finish_time' => date('Y-m-d H:i:s'),
                    ], ['id' => $order->id]);
                    $order->setAttr('order_status', 40);
                    $order->setAttr('confirm_time', date('Y-m-d H:i:s'));
                    $order->setAttr('finish_time', date('Y-m-d H:i:s'));
                    $order->setAttr('status_text', '已完成');
                }
            }
        }
    }
}